<template>
  <div class="">
    <van-nav-bar
      @click-left="$router.back()"
      left-arrow
      title="我的订单"
      fixed
    ></van-nav-bar>
    <div class="poster_type">
      <ul>
        <li :class="{ active: type == 0 }" @click="setType(0)">
          全部
          <i></i>
        </li>
        <li :class="{ active: type == 1 }" @click="setType(1)">
          已完成
          <i></i>
        </li>
        <li :class="{ active: type == 2 }" @click="setType(2)">
          待支付
          <i></i>
        </li>
      </ul>
    </div>
    <main>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        @load="onLoad"
      >
        <div class="item" v-for="item in formInfo" :key="item.id">
          <div class="title">
            <span class="spans">订单编号:{{ item.outTradeNo }}</span>
            <div class="right">
              <span v-show="item.status == 4">已取消</span>
              <span
                class="spano"
                v-show="item.orderType == 2 && item.status == 1"
                >提现成功</span
              >
              <span
                class="span"
                v-show="item.orderType == 2 && item.status == 2"
                >待审核</span
              >
              <span v-show="item.orderType == 2 && item.status == 3"
                >提现失败</span
              >
              <span
                class="spano"
                v-show="item.orderType !== 2 && item.status == 1"
                >已支付</span
              >
              <span
                class="span"
                v-show="item.orderType !== 2 && item.status == 2"
                >待支付</span
              >
              <span v-show="item.orderType !== 2 && item.status == 3"
                >支付失败</span
              >
              <span
                class="span"
                v-show="item.orderType !== 2 && item.status == 5"
                >等待退款</span
              >
              <span
                class="spano"
                v-show="item.orderType !== 2 && item.status == 6"
                >退款成功</span
              >

              <span>
                <van-icon name="delete-o" @click="del(item)" />
              </span>
            </div>
          </div>
          <div class="center">
            <div class="left">
              <img src="../../assets/images/order/user.png" alt="" />
            </div>
            <div class="right">
              <h4>{{ item.description }}</h4>
              <p>{{ item.unitPrice || "" }}</p>
            </div>
          </div>
          <div class="bottom">
            <p>{{ item.gmtCreate }}</p>
            <span
              >合计：
              <span>￥{{ item.amount }}</span>
            </span>
          </div>
          <div class="foot" v-show="item.type !== 2 && item.status == 2">
            <div class="pay" @click="pay(item.outTradeNo)">去支付</div>
          </div>
        </div>
      </van-list>
    </main>
    <!-- 弹框 -->
    <van-dialog v-model="show" :show-confirm-button="false">
      <template #title>
        <van-icon name="cross" @click="show = false" />
      </template>
      <template #default>
        <div class="cont">
          <p>确定要删除该订单信息？</p>
          <van-divider />
          <div class="foot">
            <div class="left" @click="show = false">取消</div>
            <div class="right" @click="deleteOrder">确定</div>
          </div>
        </div>
      </template>
    </van-dialog>
  </div>
</template>

<script>
// 引入echarts
export default {
  name: "",
  data() {
    return {
      searchKey: "", //搜索关键字
      type: 0, //任务类型
      formInfo: [], //表单列表
      tabType: 1,
      show: false, //弹框
      isPower: 1,
      current: {},
      loading: false, //加载状态
      finished: false, //完成
      page: 1, //页数
      limit: 8, //条数
      totalPage: 100, //总页数
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    document.querySelector("body").style.backgroundColor = "#f3f5f7";
    document.querySelector("html").style.backgroundColor = "#f3f5f7";
    this.isCustomer();
    this.orderList();
  },
  methods: {
    //触底下一页
    onLoad() {
      if (this.page >= this.totalPage) {
        this.finished = true;
        return;
      }
      this.page++;

      this.orderList();
      // 加载状态结束
      this.loading = false;
    },
    //去支付
    pay(outTradeNo) {
      this.$api
        .getWxConfig({ outTradeNo })
        .then((response) => {
          if (response.code == 0) {
            this.data = response.data;
            this.weixinPay();
          } else {
            this.$toast(response.msg);
          }
        })
        .catch((error) => {
          this.$toast("请求失败", +error);
        });
    },
    //解决微信内置对象报错
    weixinPay() {
      var that = this;
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady(),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", that.onBridgeReady());
          document.attachEvent("onWeixinJSBridgeReady", that.onBridgeReady());
        }
      } else {
        that.onBridgeReady();
      }
    },
    //微信内置浏览器类，weChatParameter对象中的参数是3.步骤代码中从后端获取的数据
    onBridgeReady() {
      var that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          debug: true,
          appId: that.data.appId, //公众号名称，由商户传入
          timeStamp: that.data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: that.data.nonceStr, //随机串
          package: that.data.package,
          signType: that.data.signType, //微信签名方式：
          paySign: that.data.paySign, //微信签名
          jsApiList: ["chooseWXPay"],
        },
        function(res) {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            //支付成功后的操作
            that.$toast({
              message: "支付成功",
              duration: 2000,
            });
            this.$router.push({
              path: "/message",
              query: {
                msg: 3,
              },
            });
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            //取消支付的操作
            that.$toast({
              message: "取消支付",
              duration: 2000,
            });
          } else {
            //支付失败的操作
            that.$toast({
              message: "支付失败",
              duration: 2000,
            });
            this.$router.push({
              path: "/message",
              query: {
                msg: 4,
              },
            });
          }
        }
      );
    },
    //点击删除
    del(item) {
      this.current = item;
      this.show = true;
    },
    //删除订单
    async deleteOrder() {
      let obj = {
        userId: this.$store.state.userInfo.id,
        outTradeNo: this.current.outTradeNo,
        userType: 2,
      };
      let res = await this.$api.deleteOrder(obj);
      if (res.code !== 0) return this.$toast(res.msg);

      this.show = false;
      this.orderList();
      this.$toast("删除成功！");
    },
    // 切换
    setType(n) {
      this.taskArr = [];

      this.type = n;
      this.orderList();
    },
    //获取订单列表
    async orderList() {
      let obj = {
        userId: this.$store.state.userInfo.account, //用户id
        userType: 2, //1普通用户2企业用户
        page: this.page,
        limit: this.limit,
      };
      if (this.type !== 0) {
        obj.status = this.type;
      } else {
        obj.status = "";
      }
      let res = await this.$api.orderList(obj);
      // console.log(res);
      if (res.code !== 0) return;
      //判断是否是第一页
      if (this.page == 1) {
        this.formInfo = res.data.list || [];
      } else {
        this.formInfo.push(...res.data.list);
      }
      this.totalPage = res.data.totalPage;
    },
    //判断是否有权限创建
    async isCustomer() {
      let userWxData = JSON.parse(sessionStorage.getItem("userWxData"));
      let account = sessionStorage.getItem("agentId");
      let res = await this.$api.isCustomer({
        openId: userWxData.openid,
        account,
        id: this.$store.state.userInfo.id,
        phone: this.$store.state.userInfo.phone,
      });
      this.isPower = res.data;
    },
  },
};
</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
.poster_type {
  padding: 55px 30px 5px;
  background-color: #fff;
  ul {
    display: -webkit-flex;
    display: flex;
    justify-content: space-between;
    li {
      font-size: 16px;
      color: #666;
      display: -webkit-flex;
      display: flex;
      justify-content: center;
      position: relative;
      align-items: center;
      padding: 5px 0;
      i {
        width: 28px;
        height: 3px;

        border-radius: 3px;
        position: absolute;
        bottom: 0;
      }
    }
    .active {
      font-weight: 700;
      color: #000;
      i {
        background-color: #0264d1;
      }
    }
  }
}
main {
  padding: 0 15px 15px;
  height: calc(100vh - 137px);
  overflow-y: scroll;
  .item {
    margin-top: 15px;
    padding: 7.5px 7.5px 13px;
    background-color: #ffffff;
    border-radius: 5px;
    .title {
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #dfdfdf;
      padding-bottom: 7px;
      .spans {
        font-size: 10px;
        color: #666666;
        letter-spacing: 1px;
        width: 230px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .right {
        color: #999999;
        span {
          font-size: 10px;
          color: #666666;
          display: inline-block;
          padding-right: 14px;
          &:last-of-type {
            display: inline-block;
            padding-left: 14px;
            padding-right: 0;
            border-left: 1px solid #999999;
          }
        }
        .span {
          color: #ff2d39;
        }
        .spano {
          color: #4dbb7b;
        }
      }
    }
    .center {
      display: flex;
      padding: 9px 0 18px;
      .left {
        width: 39px;
        height: 39px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .right {
        margin-left: 11px;

        h4 {
          font-size: 13px;
          color: #666666;
          letter-spacing: 1px;
        }
        p {
          margin-top: 6px;
          font-size: 10px;
          color: #666666;
          letter-spacing: 1px;
        }
      }
    }
    .bottom {
      display: flex;
      justify-content: space-between;
      p {
        font-size: 10px;
        color: #999999;
        letter-spacing: 1px;
      }
      span {
        font-size: 12px;
        color: #666666;
        letter-spacing: 1px;
        span {
          color: #333333;
        }
      }
    }
    .foot {
      margin-top: 14px;
      display: flex;
      justify-content: flex-end;
      .pay {
        width: 60px;
        height: 21px;
        background-color: #ffffff;
        border: 1px solid #0264d1;
        border-radius: 11px;
        font-size: 10px;
        color: #0264d1;
        letter-spacing: 1px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
/deep/ .van-dialog__header {
  text-align: right;
  padding: 15px 15px 0 0;
}
.van-dialog {
  width: 272px;
  .cont {
    font-size: 14px;
    font-weight: 700;
    color: #353535;
    text-align: center;
    p {
      padding: 20px 0;
    }
    .van-divider {
      margin: 0;
    }
    .foot {
      width: 100%;
      height: 43px;
      display: flex;
      .left,
      .right {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #999999;
      }
      .right {
        color: #009dff;
        border-left: 1px solid #f5f6f8;
      }
    }
  }
}
</style>
